<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
use App\Models\Article;

use Cache;

class SyncBaiduCitation extends Command
{

    const URL = 'http://xueshu.baidu.com/s?wd=journal%3A%28%E5%8A%A8%E7%89%A9%E5%AD%A6%E7%A0%94%E7%A9%B6%29&tn=SE_baiduxueshu_c1gjeupa&ie=utf-8&usm=1&sort=sc_cited&filter=sc_year%3D%7B2016%2C%2B%7D&sc_f_para=sc_tasktype%3D%7BfirstAdvancedSearch%7D&bcp=1&sc_hit=1';

    // const CACHE_NAME = 'baidu_cites';

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:baidu:citation';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'which can copy a list of paper order bay cites';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $cacheName = config('app.cites_cahe_name');
        // print_r(Cache::get($cacheName));exit;
        $client = new Client();
        $guzzleClient = new GuzzleClient(array(
            'timeout' => 60,
        ));
        $client->setClient($guzzleClient);

        $articles = [];
        try {
            $page = 0;
            while (true) {
                $url = self::URL . sprintf('&pn=%u0', $page);
                $crawler = $client->request('GET', $url);
                $resItems = $crawler->filterXpath('//div[@class="result sc_default_result xpath-log"]');
                $resItems->each(function ($item, $i) use (&$articles) {
                    $titleItem = $item->filterXpath('//h3/a');
                    $title = trim($titleItem->text());

                    $article = Article::where('title', 'like', substr($title, 0, -1) . '%')->first();
                    if ($article) {
                        $citeCount = $item->filterXpath('//a[@class="sc_cite_cont"]');
                        $citeCount = trim($citeCount->text());

                        $articles[$article->id] = $citeCount;
                    }
                    
                });
                $page++;

                if (count($articles) > 10) break;
            }
            
            Cache::forget($cacheName);
            $expiresAt = now()->addDays(5);
            Cache::put($cacheName, $articles, $expiresAt);

            $this->info('fetch ' . count($articles) . ' articles can cache them' );
        } catch(\Exception $e) {
            print_r($e->getMessage());
        } 
    }
}
